package one.four.fifteen;

import java.util.HashMap;
import java.util.Map;

public class ThreeSum {

	public static int fac(int n) {
		int r = 1;
		for (int i = n; i > 2; i--) {
			r *= i;
		}
		return r;
	}

	public static int c(int n, int r) {
		int res = fac(n) / (fac(n - r) * fac(r));
		return res;
	}

	public static int count(int[] a) {
		int r = 0;
		int z = 0;
		Map<Integer, Integer> pos = new HashMap<Integer, Integer>();
		Map<Integer, Integer> neg = new HashMap<Integer, Integer>();
		int tmp;
		for (int i = 0; i < a.length; i++) {
			if (a[i] == 0) {
				z++;
			}

			if (a[i] > 0) {
				if (pos.containsKey(a[i])) {
					tmp = pos.get(a[i]);
					pos.put(a[i], tmp + 1);
				} else {
					pos.put(a[i], 1);
				}
			}
			if (a[i] < 0) {
				if (neg.containsKey(a[i])) {
					tmp = neg.get(a[i]);
					neg.put(a[i], tmp + 1);
				} else {
					neg.put(a[i], 1);
				}
			}
		}
		if (z >= 3) {
			r += c(z, 3);
		}

		int posOri = 0;
		for (int i : pos.values()) {
			posOri += i;
		}

		int negOri = 0;
		for (int i : neg.values()) {
			negOri += i;
		}

		int v;
		for (int i = 0; i < a.length; i++) {
			for (int j = i + 1; j < a.length; j++) {
				if (a[i] < 0 && a[j] < 0) {
					v = a[i] + a[j];
					if (pos.containsKey(-v)) {
						tmp = pos.get(-v);
						pos.put(-v, tmp - 1);
					}
				}
			}
		}

		int posAft = 0;
		for (int i : pos.values()) {
			posAft += i;
		}
		r += (posOri - posAft);

		for (int i = 0; i < a.length; i++) {
			for (int j = i + 1; j < a.length; j++) {
				if (a[i] > 0 && a[j] > 0) {
					v = a[i] + a[j];
					if (neg.containsKey(-v)) {
						tmp = neg.get(-v);
						neg.put(-v, tmp - 1);
					}
				}
			}
		}

		int negAft = 0;
		for (int i : neg.values()) {
			negAft += i;
		}
		r += (negOri - negAft);

		return r;
	}

	public static void main(String[] args) {
		int[] a = { 1, 1, -2, 5, 5, -10, 0, 3, 0, 4, 0 };
		int r = count(a);

		System.out.println(r);
	}

}
